<template>
  <Drawer class-name="drawer-header" :title="`${$t('ledger.AddTransferEquipment')}`" v-model="changeDeviceVisible"
          width="720" :scrollable="true" :mask-closable="false"
          :styles="styles" :transfer="false">
    <Form label-position="top" class="changeDeviceModal">
      <Row :gutter="24">
        <Col span="12">
          <FormItem :label="$t('common.Entity')" required>
            <Select :disabled="isEdit" style="width: 100%" v-model="searchParams.useCompanyId"
                    @on-change="handleFactoryChange" clearable
                    :placeholder="`${$t('common.selectInfo')}`">
              <Option v-for="(item, index) of factoryList" :value="item.id" :key="index">{{ item.name }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem :label="$t('preliminary.Location')" label-position="top" required>
            <Cascader :disabled="isEdit" change-on-select v-model="orgId" :data="orgList" :transfer="true"
                      @on-change="handleCasChange"></Cascader>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem :label="$t('maintenance.EquipmentNo')" label-position="top">
            <Input v-model="searchParams.deviceNo" :placeholder="`${$t('common.inputInfo')}`"/>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem :label="$t('maintenance.EquipmentName')" label-position="top">
            <Input v-model="searchParams.deviceName" :placeholder="`${$t('common.inputInfo')}`"/>
          </FormItem>
        </Col>

        <Col span="12">
          <FormItem :label="$t('equipCheck.SerialNo')" label-position="top">
            <Input v-model="searchParams.deviceMId" :placeholder="$t('equipCheck.SerialNo')"/>
          </FormItem>
        </Col>

        <Col span="12">
          <FormItem :label="$t('equipmentscrapped.CostCenter')" required label-position="top">
            <Select v-model="searchParams.costCenter"
                    filterable
                    :disabled="isEdit"
                    clearable
                    :placeholder="$t('equipmentscrapped.CostCenter')"
                    :remote-method="getCenterList"
                    @on-select="coseCenterSelect"
                    :loading="loading">
              <Option v-for="(item,index) of centerList"
                      :value="item.costCenter"
                      :key="index"
                      :tag="item.useDept"
                      :label="item.ktextName"/>
            </Select>
          </FormItem>
        </Col>

        <Col span="12">
          <Button type="primary" class="ivu-btn-lg" style="margin-top: 21px" @click="changePageNum(1)">
            {{ $t('common.Query') }}
          </Button>
        </Col>
      </Row>
    </Form>
    <div style="margin-top: 10px;" class="tableContent">
      <Table row-key="id" :columns="columns" :data="dataSource" @on-selection-change="handleSelectionChange">
        <template slot-scope="{ row }" slot="costCenter">
          <span>{{ row.useDept }} - {{ row.costCenter }}</span>
        </template>
      </Table>
      <div class="pageWrap mt16">
        <pageLeftTitle :total="total" :selected="selectSource.length"/>
        <Page :total="total" :page-size="pageSize" :page-size-opts="$variable.pageSizes" :current="pageNum"
              @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total/>
      </div>
    </div>
    <div class="demo-drawer-footer">
      <Button class="ivu-btn-lg" style="margin-right: 8px" @click="changeDeviceVisible = false">
        {{ $t('common.Cancle') }}
      </Button>
      <Button class="ivu-btn-lg" type="primary" @click="handleOk">{{ $t('maintenance.Confirmed') }}</Button>
    </div>
  </Drawer>
</template>

<script>
import recursion from "../../../../util/recursion";
import {findOrgByToken} from '@/api/index.js'

export default {
  name: "changesDeviceModal",
  data() {
    return {
      companyCode: '',
      costCenter: '',
      loading: false,
      changeDeviceVisible: false,
      total: 0,
      pageNum: 1,
      pageSize: 10,
      pageSizeOption: [10, 20, 30],
      styles: {
        height: 'calc(100% - 55px)',
        overflow: 'scroll',
        paddingBottom: '53px',
        position: 'static'
      },
      searchParams: {},
      factoryList: [],
      centerList: [],
      columns: [
        {
          type: 'selection',
          minWidth: 60,
          align: 'center',
          fixed: 'left'
        },
        {
          title: `${this.$t('maintenance.EquipmentName')}`,
          key: 'deviceName',
          align: 'center',
          minWidth: 120,
          // render: (h, params) => {
          //     return h('div', params.row.status === 0 ? '非台账' : params.row.status === 1 ? '已验收' : '已入账')
          // }
        },
        {
          title: `${this.$t('equipCheck.SerialNo')}`,
          key: 'deviceMId',
          align: 'center',
          minWidth: 160
        },
        {
          title: `${this.$t('maintenance.EquipmentNo')}`,
          key: 'deviceNo',
          align: 'center',
          minWidth: 160
        },
        {
          title: `${this.$t('equipCheck.AssetNo')}`,
          key: 'assetsNo',
          align: 'center',
          minWidth: 160
        },
        {
          title: `${this.$t('equipCheck.Model')}`,
          key: 'specification',
          align: 'center',
          minWidth: 120,
        },

        {
          title: `${this.$t('设备等级')}`,
          key: 'categoryName',
          align: 'center',
          minWidth: 120
        },
        {
          title: `${this.$t('preliminary.DeviceOwner')}`,
          key: 'equipmentManager',
          align: 'center',
          minWidth: 120
        },
        {
          title: `${this.$t('equipmentscrapped.CostCenter')}`,
          slot: 'costCenter',
          align: 'center',
          minWidth: 220
        },
        // {
        //     title: `${ this.$t('common.operation') }`,
        //     slot: "action",
        //     width: 180,
        //     align: "center",
        //     fixed: 'right',
        // }
      ],
      dataSource: [],
      orgList: [],//功能位置
      selectSource: [],
      oldOrgIdlist: [],
      orgId: [],
      isEdit: false
    }
  },
  created() {
    this.getCenterList();
    this.getOrgList()
    this.getCompanyList()
  },
  methods: {
    coseCenterSelect(val) {
        this.searchParams.costCenterName = val.tag;
    },
    getOrgList() {
      let params = {
        level: 3
      }
      findOrgByToken(params).then(res => {
        if (res.code === 200) {
          const obj = {
            label: 'name',
            value: 'code',
            children: 'children',
            id: 'id'
          }
          this.orgList = recursion.convertTree(res.data, obj)
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    handleCasChange(val, selectedData) {

      this.searchParams.orgId = val[val.length - 1]

      let arr = [];
      selectedData.forEach(item => {
        arr.push(item.id);
      });
      this.oldOrgIdlist = arr;
    },
    getCenterList(query) {
      if (query !== '') {
        this.axios({
          method: 'get',
          url: '/dms/dmsDevice/getCostCenter',
          params: {
            costCenter: query
          }
        }).then(res => {
          if (res.code === 200) {
            this.centerList = res.data.map(center => {
              return {
                ...center,
                ktextName: `${center.costCenter}-${center.useDept}`
              }
            })
            this.costCenter = query
          } else {
            this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
          }
        })
      } else {
        this.centerList = []
      }
    },
    getCompanyList() {
      this.axios({
        method: 'get',
        url: '/basic/company/getCompanyListByUser',
        params: {}
      }).then(res => {
        if (res.code === 200) {
          let arr = res.data.map(item => {
            return {
              ...item,
              id: item.id.toString()
            }
          })
          this.factoryList = arr
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    show({orgId, useCompanyId, code, costCenter}, isEdit) {
      this.isEdit = isEdit > 0 ? true : false
      this.searchParams = {}
      if (this.isEdit) {
        this.orgId = orgId
        this.oldOrgIdlist = code
        this.searchParams.orgId = orgId[orgId.length - 1]
        this.searchParams.useCompanyId = useCompanyId
        this.searchParams.costCenter = costCenter
        this.changePageNum(1)
      } else {
        this.orgId = []
        this.oldOrgIdlist = []
        this.searchParams.orgId = ''
        this.searchParams.useCompanyId = this.factoryList && this.factoryList.length > 0 ? this.factoryList[0].id : '';
      }

      this.dataSource = []
      this.changeDeviceVisible = true

    },
    handleFactoryChange(val) {

      this.companyCode = this.factoryList.filter(item => item.id == val)[0].code
    },
    handleSelectionChange(data) {
      // console.log(data)
      this.selectSource = [...data]
    },
    handleOk() {
      this.changeDeviceVisible = false
      this.$emit('handleMulDevice', this.selectSource, {
        useCompanyId: this.searchParams.useCompanyId,
        orgId: this.oldOrgIdlist,
        costCenter: this.searchParams.costCenter,
        costCenterName: this.searchParams.costCenterName,
        realOrgId: this.orgId
      })
    },
    //分页
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    searchList() {
      if (!this.searchParams.useCompanyId) {
        this.$Message.warning(({content: '请选择所属公司!', duration: 6, closable: true}));
        return false
      }
      if (!this.searchParams.orgId) {
        this.$Message.warning(({content: '请选择安装位置!', duration: 6, closable: true}));
        return false
      }
      if (!this.searchParams.costCenter) {
        this.$Message.warning(({content: '请选择成本中心!', duration: 6, closable: true}));
        return false
      }
      let params = {
        companyId: this.tagName,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      for (let key in this.searchParams) {
        if (this.searchParams[key]) {
          this.$set(params, key, this.searchParams[key])
        }
      }
      params.code = params.orgId
      delete params.orgId
      this.axios({
        method: 'get',
        url: '/dms/dmsMoveApply/getDeviceList',
        params: params
      }).then(res => {
        
        if (res.code === 200) {
          this.dataSource = res.data.list
          this.total = res.data.total
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
  }
}
</script>

<style scoped>
.demo-drawer-footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}


</style>

<style lang="scss">
.changeDeviceModal {
  .ivu-form-item {
    height: 63px;
  }
}
</style>
